//
//  MessagesViewController.m
//  UADE-Mobile
//
//  Created by Marcos Damian Pianelli on 11/10/11.
//  Copyright (c) 2011 DG. All rights reserved.
//

#import "MessagesViewController.h"
#import "TTMessagesDataSource.h"

@implementation MessagesViewController
@synthesize groupID, userInfo;


-(void)post{
    
    TTPostController* controller = [[TTPostController alloc] init];
    [controller showInView:self.view animated:TRUE];
    controller.Delegate = self;
                                    //[NSDictionary dictionaryWithObjectsAndKeys:@"Default Text", @"text", nil]
    //  controller.originView = self.tableView;
    //[controller openURLFromButton: self.navigationItem.rightBarButtonItem];
    
    
}

-(void)refreshGroupInfo{
    NSLog(@"refreshGroupinfo");
    [[StudentModel SharedInstance] fetchGroupWithDelegate:self aulaID:self.groupID forceFetch:TRUE];
}


-(id)initWithGroupID:(NSString*)IDGrupo{
    
    
    if (self = [super init]) {
        
        self.groupID = IDGrupo;
        
        /* self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Close", @"") style:UIBarButtonItemStyleBordered target:self action:@selector(closeAction:)];
        */
        
        self.variableHeightRows = TRUE;
        self.title = NSLocalizedString(@"Messages", @"");
        
        //self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self  action:@selector(post)];
        
        
        UIToolbar *tools = [[UIToolbar alloc]
                            initWithFrame:CGRectMake(0.0f, 0.0f, 95.0f, 44.01f)]; // 44.01 shifts it up 1px for some reason
        tools.clearsContextBeforeDrawing = NO;
        tools.clipsToBounds = NO;
        tools.tintColor = RGBCOLOR(38,92,139);
        tools.barStyle = self.navigationController.navigationBar.barStyle;
        NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:2];
        
        // Create a standard refresh button.
        UIBarButtonItem *bi = [[UIBarButtonItem alloc]
                               initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(post)];
        bi.style = UIBarButtonItemStyleBordered;
        [buttons addObject:bi];
        
        // Add profile button.
        bi = [[UIBarButtonItem alloc]
                               initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshGroupInfo)];
        bi.style = UIBarButtonItemStyleBordered;

        [buttons addObject:bi];
        
        // Add buttons to toolbar and toolbar to nav bar.
        [tools setItems:buttons animated:NO];
        UIBarButtonItem *twoButtons = [[UIBarButtonItem alloc] initWithCustomView:tools];
        self.navigationItem.rightBarButtonItem = twoButtons;

    }
    
    return self;
    
    
    
}


-(void)didGetGroupInfo:(id)model withError:(NSError*)error{ 

    if (!error) {

        self.userInfo = model;
        
        NSMutableArray * items = [NSMutableArray array];
        
        
        for( NSDictionary * eachMessage in [self.userInfo objectForKey:@"Mensajes"]){        
            
            [items addObject:[TTTableMessageItem itemWithTitle:[eachMessage objectForKey:@"Usuario"] caption:[eachMessage objectForKey:@"Fecha"] text:[eachMessage objectForKey:@"Texto"] timestamp:nil URL:nil]];
            //   [items addObject:[TTTableSubtextItem itemWithText:[eachMessage objectForKey:@"Usuario"] caption:[eachMessage objectForKey:@"Texto"]]];
            
            
        }
        
        
        self.dataSource = [TTMessagesDataSource dataSourceWithItems:items];
    }
    else {
        NSLog(@"error: %@", error.description);
    }

}

#pragma mark - Post Controller Delegate


- (BOOL)postController:(TTPostController*)postController willPostText:(NSString*)text{
    return TRUE;
}

/**
 * The text will animate towards a rectangle.
 *
 * @return the rect in screen coordinates where the text should animate towards.
 */
/*- (CGRect)postController:(TTPostController*)postController willAnimateTowards:(CGRect)rect{
    
}*/

/**
 * The text has been posted.
 */
- (void)postController: (TTPostController*)postController
           didPostText: (NSString*)text
            withResult: (id)result{
    
    if([text length] > 0)
        [[StudentModel SharedInstance] addGroupMessage:text toGroup:[self.userInfo objectForKey:@"ID"]  withDelegate:self];

}

/**
 * The controller was cancelled before posting.
 */
- (void)postControllerDidCancel:(TTPostController*)postController{
    
}


-(void)didAddGroupMessage:(id)model withError:(NSError*)error{
   
    if( error == nil){
       [[StudentModel SharedInstance] fetchGroupWithDelegate:self aulaID:self.groupID forceFetch:TRUE];
    }

    
    
}



- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[StudentModel SharedInstance] fetchGroupWithDelegate:self aulaID:self.groupID];
    //timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(refreshGroupInfo) userInfo:nil repeats:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end
